package com.bocloud.cmp.service.app.monitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.alibaba.fastjson.JSONArray;
import com.bocloud.cmp.entity.app.resource.OpenshiftMonitor;
import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.BaseResult;
import com.bocloud.common.model.Result;
import com.bocloud.common.utils.ListTool;
/**
 * @author Zaney
 * @data:2017年4月20日
 * @describe:第二次线程池client
 */
@Repository("appSecondClient")
public class AppSecondClient {
	private static Logger logger = LoggerFactory.getLogger(AppSecondClient.class);
	@SuppressWarnings("unused")
	private HttpClient httpClient;

	public void setHttpClient(HttpClient httpClient) {
		this.httpClient = httpClient;
	}

	public Result url(OpenshiftMonitor monitor){
		HttpClient httpClient = new HttpClient();
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("Authorization", "Bearer " + monitor.getToken());
		hashMap.put("Hawkular-Tenant", monitor.getNamespace());
		String url = "https://" + monitor.getDomainName() + "/hawkular/metrics/" + monitor.getAccess() + "/data?"
					+ "stacked=true&tags=descriptor_name:" + monitor.getDescripteName() + ",type:"
					+ monitor.getType() + ",labels:" + monitor.getLabels() + "&bucketDuration="
							+ monitor.getBucketDuration() + "ms&start=" + monitor.getStartTime();
		logger.info(monitor.getResourceType()+"namespace: "+monitor.getNamespace());
		logger.info(monitor.getResourceType()+"访问的url: "+url);
		Result result = httpClient.get(hashMap, null, url);
		return result;
	}
	
	/**
	 * 线程池任务
	 * @param monitors
	 * @return
	 * @throws Exception
	 */
	public List<JSONArray> batch(List<OpenshiftMonitor> monitors) throws Exception {
		ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
		CompletionService<BaseResult<JSONArray>> completionService = new ExecutorCompletionService<>(executor);
		if (ListTool.isEmpty(monitors)) {
			return null;
		}
		for (OpenshiftMonitor monitor : monitors) {
			AppSecondTask task = new AppSecondTask(monitor);
			completionService.submit(task);
		}
		List<JSONArray> objectList = new ArrayList<JSONArray>();
		int completeTask = 0;
		int timeout = 1000 * 60 * 10;
		long begingTime = System.currentTimeMillis();
		while (completeTask < monitors.size()) {
			Future<BaseResult<JSONArray>> take = completionService.take();
			if (null != take) {
				BaseResult<JSONArray> result = take.get();
				if (result.isSuccess()) {
					objectList.add((JSONArray) result.getData());
				}
				completeTask++;
				if (System.currentTimeMillis() - begingTime > timeout) {
					break;
				}
			}
		}
		executor.shutdown();
		return objectList;
	}
}
